//
//  SLWebVC.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/13.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import UIKit
import WebKit
import SwiftyJSON
import MBProgressHUD
import StoreKit
class SLWebVC: SLBaseVC ,WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler{
    var url:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = ""
        self.navigationView.onClickLeftButton = {
            if self.WkWebView.canGoBack {
                self.WkWebView.goBack()
            }else{
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    override func loginEventAction() {
        super.loginEventAction()
        self.loadUrl(url: self.url)
    }
    lazy var WkWebView:WKWebView  = {
        let c = WKWebViewConfiguration()
        c.userContentController.add(self, name: "InStoreys")
        c.userContentController.add(self, name: "AreNor")
        c.userContentController.add(self, name: "ArchitectureAnd")
        c.userContentController.add(self, name: "PeriodHeritage")
        c.userContentController.add(self, name: "SandstoneIndoislamic")
        c.userContentController.add(self, name: "SitesIs")
        c.userContentController.add(self, name: "BeingSouth")
        c.userContentController.add(self, name: "VeryArchitecture")
        c.userContentController.add(self, name: "AndArchitecture")
        c.userContentController.add(self, name: "AndDwarka")
        c.userContentController.add(self, name: "WithinBetween")

        c.selectionGranularity = .dynamic
        c.allowsInlineMediaPlayback = true
        let p = WKWebpagePreferences()
        p.allowsContentJavaScript = true
        c.defaultWebpagePreferences = p
        let v = WKWebView(frame: .zero, configuration: c)
        v.backgroundColor = .white
        v.uiDelegate = self
        v.navigationDelegate = self
        //添加
        self.view.addSubview(v)
        v.snp.makeConstraints { make in
            make.top.equalTo(self.navigationView.snp.bottom)
            make.left.right.bottom.equalTo(0)
            
        }
        return v
    }()
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
           guard let url = navigationAction.request.url else {
               decisionHandler(.allow)
               return
           }
        if url.scheme! == "fon:" {
            let string = url.absoluteString
            jump(url: string )
        }
               decisionHandler(.allow)
       }
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
            
        print(message.name)
        let name = message.name
        var applink = ""
        if let body = message.body as? [String],
           let link = body.first{
            applink = link
        }
        if name == "InStoreys"{//页面跳转
            jump(url: applink)
        }
        if name=="AreNor"{//关闭当前webview
            self.navigationController?.popViewController(animated: true)
        }

        if name=="ArchitectureAnd"{//带参数页面跳转
            
            jump(url: applink )
            
        }
        if name=="PeriodHeritage"{//回到首页，并关闭当前页
            self.navigationController?.popToRootViewController(animated: true)
            if let rootVC = UIApplication.shared.delegate?.window??.rootViewController as? SLTabBarController{
                rootVC.selectedIndex = 0
            }
        }
        if name=="SandstoneIndoislamic"{//回到个人中心，并关闭当前页
            self.navigationController?.popToRootViewController(animated: true)
            //以下是跳转相关
            if let rootVC = UIApplication.shared.delegate?.window??.rootViewController as? SLTabBarController{
                rootVC.selectedIndex = 2
            }

        }
        if name=="SitesIs"{//跳转到登录页，并清空页面栈
            self.navigationController?.popToRootViewController(animated: true)
            GoToLoginVC()
        }
        if name=="BeingSouth"{//拨打电话号码（客户端补充"tel:"）
            if let url = URL(string: "tel://\(applink)"), UIApplication.shared.canOpenURL(url) {
                        UIApplication.shared.open(url, options: [:], completionHandler: nil)
                    } else {
                        print("无法拨打电话")
                    }
        }
        if name=="AndArchitecture"{//确认申请埋点调用方法
            let body = message.body as! [Any]
                
            let id = "\(body.first ?? "")"
            SLHttpTool.AsyncUploadData(mahathat: "10",extended: id,thais: "", target: self, finishCallBack: { responseData, success, msg, code in
            })
        }
        if name=="VeryArchitecture"{// app store评分功能
            if let windowScene = UIApplication.shared.windows.first?.windowScene {
                SKStoreReviewController.requestReview(in: windowScene)
            }
        }
        if name=="AndDwarka"{// 开始绑卡时间
            self.startDate = Int(Date().timeIntervalSince1970)
            
        }
        if name=="WithinBetween"{// 结束绑卡时间
            SLHttpTool.AsyncUploadData(mahathat:"8", thais: "\(self.startDate)", target: self) { responseCall, success, msg, code in
                
            }
        }
        
    }
    func loadUrl(url:String) {
        if !url.isEmpty {
            self.url = url
            var finalUrl = ""
            finalUrl = StringJoinParameter(url: url)
            self.WkWebView.load(NSURLRequest(url: NSURL(string:finalUrl)! as URL) as URLRequest)
        }else {
            MBProgressHUD.showError(error: "")
        }
    }
    /// 拼接其他参数
     func StringJoinParameter(url:String,dic:Dictionary<String, Any>? = nil) -> String {
         let none = SLTool.getVersion()
         let classic = SLTool.getDeviceModel()
         let gaze = SLKeychain.getIDFV()
         let hair = SLUserAccount.default.hair
         let symbolically = SLKeychain.getIDFA()
         let splendour = SLUserAccount.default.sessionId
         let providing = SLTool.getSystemVersion()
         var bodyDic = Dictionary<String, Any>()
         if let dic = dic{
             for item in dic {
                 bodyDic.updateValue(item.value, forKey: item.key)
             }
         }
         bodyDic.updateValue(none, forKey:"none" )
         bodyDic.updateValue(classic, forKey:"classic" )
         bodyDic.updateValue(gaze, forKey:"gaze" )
         bodyDic.updateValue(hair, forKey: "hair")
         bodyDic.updateValue(symbolically, forKey:"symbolically" )
         bodyDic.updateValue(splendour, forKey:"splendour" )
         bodyDic.updateValue(providing, forKey:"providing" )
         var baseUrl: String = url
         if !baseUrl.contains("?"){
             baseUrl = baseUrl + "?"
         }
         if baseUrl.contains("="){
             baseUrl = baseUrl + "&"
         }
        var params:[String] = []
        for dic in bodyDic{
            params.append("\(dic.key)=\(dic.value)")
        }
        baseUrl = baseUrl + params.joined(separator: "&")
        return baseUrl
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        let title = webView.title
        self.title = title
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            let title = self.WkWebView.title
            self.title = title
        }
    }
}
